package spring.data.jpa.repository.support;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;

import spring.data.jpa.repository.support.SearchFilter.Operator;

public class JpaSearchSupport extends FilterSupport{

	/**
	 * <pre>
	 * searchParams中key的格式为OPERATOR_FIELDNAME
	 * 1.LIKE_username,jsp:search_LIKE_username
	 * 2.LIKE_username_OR_LIKE_email_OR_EQ_mobile 
	 * 如果为 2 类型,map的value值可以是一个,则多个or条件对应一个值;
	 * 也可以是多个,则这多个值数组必须和or的条件个数一一对应,比如上面有三个Or条件,
	 * 分别是usernam,email,mobile,则object数组必须有3个值
	 * </pre>
	 */
	public JpaSearchSupport parse(Map<String, Object> searchParams) {
		for (Entry<String, Object> entry : searchParams.entrySet()) {
			// 过滤掉空值
			String key = entry.getKey();
			Object value = entry.getValue();
			if (StringUtils.isBlank(value.toString().trim())) {
				continue;
			}
			if (key.contains(SearchFilter.OR_SEPARATOR)) {
				// Or解析
				String[] keys = key.split(SearchFilter.OR_SEPARATOR);
				if (value.getClass().isArray()) {
					// 是数组
					Object[] values = (Object[]) value;
					if (keys.length == values.length) {
						for (int i = 0; i < keys.length; i++) {
							if (StringUtils.isBlank(values[i].toString().trim())) {
								continue;
							}
							SearchFilter filter = buildSearchFilter(keys[i], values[i]);
							this.or(filter);
						}
					}
				} else {
					for (int i = 0; i < keys.length; i++) {
						if (StringUtils.isBlank(value.toString().trim())) {
							continue;
						}
						SearchFilter filter = buildSearchFilter(keys[i], value);
						this.or(filter);
					}
				}
			} else {
				if (value.getClass().isArray()) {
					Object[] values = (Object[]) value;
					for (int i = 0; i < values.length; i++) {
						if (StringUtils.isBlank(values[i].toString().trim())) {
							continue;
						}
						SearchFilter filter = buildSearchFilter(key, values[i]);
						this.or(filter);
					}
				} else {
					if (StringUtils.isBlank(value.toString().trim())) {
						continue;
					}
					SearchFilter filter = buildSearchFilter(key, value);
					this.and(filter);
				}

			}
		}
		return this;
	}

	private SearchFilter buildSearchFilter(String key, Object value) {
		// 拆分operator与filedAttribute
		String[] names = StringUtils.split(key, "_");
		if (names.length != 2) {
			throw new IllegalArgumentException(key + " is not a valid search filter name");
		}
		String filedName = names[1];
		Operator operator = Operator.valueOf(names[0]);

		// 创建searchFilter
		return new SearchFilter(filedName, operator, value);
	}

}
